package com.wst.system.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileHashUtil {

    // 计算 byte[] 的 SHA-256 值
    public static String calculateSHA256(byte[] input) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = digest.digest(input);
        return bytesToHex(hashBytes);
    }

    // 计算 byte[] 的 MD5 值
    public static String calculateMD5(byte[] input) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] hashBytes = digest.digest(input);
        return bytesToHex(hashBytes);
    }

    // 将 byte[] 转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    // 计算文件的 MD5 值
    public static String getFileMD5(File file) throws IOException, NoSuchAlgorithmException {
        return getFileHash(file, "MD5");
    }

    // 计算文件的 SHA-256 值
    public static String getFileSHA256(File file) throws IOException, NoSuchAlgorithmException {
        return getFileHash(file, "SHA-256");
    }

    // 通用方法计算文件的哈希值
    private static String getFileHash(File file, String algorithm) throws IOException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] byteArray = new byte[1024];
            int bytesCount;
            while ((bytesCount = fis.read(byteArray)) != -1) {
                digest.update(byteArray, 0, bytesCount);
            }
        }
        byte[] hashBytes = digest.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        File file = new File("C:\\Users\\CETC\\Pictures\\640 (1).jpg"); // 替换为实际的文件路径
        try {
            String md5 = getFileMD5(file);
            String sha256 = getFileSHA256(file);
            System.out.println("MD5: " + md5);
            System.out.println("SHA-256: " + sha256);
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
